<?php
/**
 * Created by 橙橙同学.
 * User: 橙橙同学
 * Date: 2017/11/13
 * Time: 下午10:44
 */

namespace app;
class Park
{


    /**
     * @author:橙橙同学
     * @func:生成停车订单
     */
    public static function generateParkOrder()
    {

    }



    /**
     * 记录车辆入场
     *
     * @param $data
     */
    public static function setEntry($data)
    {
        $db = self::DbLink();
        try {
            $db->beginTransaction();

            /**
             * 添加会员记录
             */
            if ($user = self::getUser($data['uid'])) {
                $park_id = $user['id'];
            } else {
                $park_user = array(
                    'openid'   => $data['openid'],
                    'uid'      => $data['uid'],
                    'mobile'   => $data['mobile'],
                    'realname' => $data['realname'],
                    'create_time' => time()
                );
                $park_id   = $db->insert('ims_park_member', $park_user);
            }

            if (empty($park_id)) {
                throw new Exception('表 [ims_park_member] 写入数据失败');
            }

            /**
             * 添加会员入场记录
             */
            $park_entry    = array(
                'park_id'     => $park_id,
                'platenumber' => $data['platenumber'],
                'entry_time'  => $data['entry_time'],
                'status'      => 0,
                'create_time' => time()
            );
            $park_entry_id = $db->insert('ims_park_entry', $park_entry);

            if (empty($park_entry_id)) {
                throw new Exception('表 [ims_park_entry] 写入数据失败');
            }

            /**
             * 同步会员积分
             */
            Payment::syncScore($data['uid'],$data['openid']);

            /**
             * 对于绑定车牌未送积分的用户赠送1000积分
             *
             */
            $count = $db->count('ims_park_platenumber_log',array('uid'=>$data['uid']));
            if ($count == 0) {
                $scoreLogsId = $db->insert('ims_park_platenumber_log',array('uid'=>$data['uid'],'create_time'=>time()));
                if ($scoreLogsId) {
                    $db->update('ims_park_member',array('score[+]'=>1000),array('uid'=>$data['uid']));
//                    $temp = Wechat::scoreConsume(array('openid'=>$data['openid'],'mobile'=>$data['mobile'],'realname'=>$data['realname']));
//                    Wechat::sendTemplateMessage($temp);
                }
            }

            $db->commit();

        } catch (Exception $e) {
            logs($e->getMessage(), 'Park');
            $db->rollback();
        }
    }

    public static function setLeave($data)
    {
        $db = self::DbLink();
        try {
            $db->beginTransaction();

            /**
             * 添加绑定车牌会员记录
             */
            if ($user = self::getUser($data['uid'])) {
                $park_id = $user['id'];
            } else {
                $park_user = array(
                    'openid'   => $data['openid'],
                    'uid'      => $data['uid'],
                    'mobile'   => $data['mobile'],
                    'realname' => $data['realname'],
                    'create_time' => time()
                );
                $park_id   = $db->insert('ims_park_member', $park_user);
            }

            if (empty($park_id)) {
                throw new Exception('表 [ims_park_member] 写入数据失败');
            }

            /**
             * 添加离场记录
             */
            $park_leave    = array(
                'park_id'     => $park_id,
                'platenumber' => $data['platenumber'],
                'leave_time'  => $data['leave_time'],
                'score'       => $data['score'],
                'amount'      => $data['amount'],
                'duration'    => $data['duration'],
                'prestore'    => $data['prestore'],
                'create_time' => time()
            );
            $park_leave_id = $db->insert('ims_park_leave', $park_leave);

            if (empty($park_leave_id)) {
                throw new Exception('表 [ims_park_entry] 写入数据失败');
            }

            $upEntry = $db->update('ims_park_entry', array('status' => 1), array(
                'AND' => array(
                    'park_id' => $park_id,
                    'status'  => 0
                )
            ));

            if ($upEntry === false) {
                throw new Exception('表 [ims_park_entry] 更新状态数据失败');
            }

            /**
             * 同步会员积分
             */
            Payment::syncScore($data['uid'],$data['openid']);

            $db->commit();

        } catch (Exception $e) {
            logs($e->getMessage(), 'Park');
            $db->rollback();
        }
    }

    public static function setUserScore($uid, $score)
    {
        $db = self::DbLink();
        try {
            $db->beginTransaction();
            $result = $db->update('ims_park_member', array('score[-]' => $score), array('uid' => $uid));
            logs('用户uid: '.$uid.' 停车场扣除('.$score.')积分。时间：'.date('Y-m-d H:i:s'),'setScore');
            if ($result === false) {
                throw new Exception('设置积分错误');
            }
            $db->commit();
            return true;
        } catch (Exception $e) {
            logs($e->getMessage(), 'Park');
            $db->rollback();
            return false;
        }
    }

    public static function setParkLog($uid, $plateNumber, $amount, $parkScore = 0, $erpScore = 0, $pay = 0)
    {
        $db = self::DbLink();

        $userInfo = $db->query("SELECT m.uid,f.openid,m.mobile,m.realname,m.nickname,m.idcard,c.custid,c.cardsn FROM ims_mc_members as m, ims_mc_mapping_fans as f, ims_mc_card_members as c WHERE m.uid = f.uid AND m.uid = c.uid AND m.uid = {$uid} LIMIT 0,1")->fetch(PDO::FETCH_ASSOC);
        if (empty($userInfo))
            return false;

        $park_id      = $db->get('ims_park_member', 'id', array('uid' => $userInfo['uid']));
        $getEntryInfo = $db->get('ims_park_entry', array('platenumber', 'entry_time'), array('AND' => array('park_id' => $park_id, 'status' => 0), 'ORDER' => 'create_time DESC'));

        if (!empty($getEntryInfo['entry_time'])) {
            $duration  = number_format((time() - strtotime($getEntryInfo['entry_time'])) / 3600, 2, '.', '');
            $entryTime = $getEntryInfo['entry_time'];
        } else {
            $duration  = $amount/3;
            $entryTime = '0000-00-00 00:00:00';
        }

        $data = array(
            'uid'         => $userInfo['uid'],
            'openid'      => $userInfo['openid'],
            'mobile'      => $userInfo['mobile'],
            'realname'    => $userInfo['realname'],
            'nickname'    => $userInfo['nickname'],
            'idcard'      => $userInfo['idcard'],
            'custid'      => $userInfo['custid'],
            'cardsn'      => $userInfo['cardsn'],
            'platenumber' => $plateNumber,
            'entrytime'   => $entryTime,
            'leavetime'   => date('Y-m-d H:i:s', time()),
            'duration'    => $duration,
            'amount'      => $amount,
            'erpscore'    => $erpScore,
            'parkscore'   => $parkScore,
            'create_time' => time(),
            'pay'         => $pay
        );
        logs(json_encode($data), 'setParkLog');
        $result = $db->insert('ims_park_logs', $data);
        if ($result) {
            return true;
        } else {
            //logs('ims_park_logs 写入失败： ' . json_encode($db->error()), 'Park');
        }
    }

    public static function getUser($uid)
    {
        $db   = self::DbLink();
        $user = $db->get('ims_park_member', '*', array('uid' => $uid));
        if (empty($user)) {
            return false;
        } else {
            return $user;
        }
    }

    private static function DbLink()
    {
        $db = new medoo(C('mysql'));
        return $db;
    }
}